import {
  ProFormDependency,
  ProFormText,
  ProFormSwitch,
  ProFormItem,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
} from '@ant-design/pro-form';
import { useState, useRef, useEffect } from 'react';
import { useDispatch } from 'umi';
import ChooseGoods from '@/components/ChoseGoods';
import ColorPicker from '@/components/ColorPicker';
import { cloneDeep, values } from 'lodash';
import { Tag, Segmented, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { querypullDownList } from '@/services/management.service';
import CommonUpload from '@/components/CommonUpload';
import { UPLOAD_FOLDER } from '@/constants/global.const';

import {
  rules,
  TPL_TYPE,
  GDCE_OPTION,
  BOR_STYLE,
  SOURCE_OPTION,
  enumCategory,
  BG_OPTION,
} from '..';
import ImageRadio from '../../../costomFields/imageRadio';
import WrapperForm from '../../wrapperForm';
import FormJumpPage from '../../../costomFields/formJumpPage';

import styles from './index.less';

import type { GoodsValue } from '..';
import type { Rule } from 'antd/lib/form';
import type { RadioChangeEvent } from 'antd';

interface IGoodsFormProps {
  data: GoodsValue;
  goodsList: any;
}

const GoodsForm: React.FunctionComponent<IGoodsFormProps> = (props) => {
  const dispatch = useDispatch();
  const wrapRef = useRef<any>(); //实例 WrapperForm，修改绑定的表单数据
  const [chooseGoodsVisible, setChooseGoodsVisible] = useState(false);
  const [selectInfo, setSelectInfo] = useState<any>([]); // 已经挑选的商品信息
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);

  const updateFromData = (val: { id: number; value: any }[]) => {
    wrapRef.current?.formRef.setFieldValue('goodsData', val);
    dispatch({
      type: 'decoration/updateData',
      payload: { goodsData: val },
    });
  };

  const updateCateInfo = (val: any) => {
    wrapRef.current?.formRef.setFieldValue('cateInfo', val);
    dispatch({
      type: 'decoration/updateData',
      payload: { cateInfo: val },
    });
  };

  //  查询商品列表
  const initGoodsList = async (type?: number) => {
    const goodsCategoryBro = wrapRef.current?.formRef.getFieldValue('goodsCategory');
    if (goodsCategoryBro !== 0 && !goodsCategoryBro) {
      return;
    }
    const params: any = {
      type: goodsCategoryBro, // 0 虚拟商品 1 实物商品
    };

    const goodsSourceRadio = wrapRef.current?.formRef.getFieldValue('goodsSourceRadio');
    const goodsChooseRadio = wrapRef.current?.formRef.getFieldValue('goodsChooseRadio');
    if (
      goodsSourceRadio === SOURCE_OPTION.marketGoods.value &&
      goodsChooseRadio === GDCE_OPTION.auto.value
    ) {
      const goodsDisplayNum = wrapRef.current?.formRef.getFieldValue('goodsDisplayNum') || 0;
      // initGoodsList();
      const current = props.goodsList.slice(0, goodsDisplayNum);
      setSelectInfo([]);
      updateFromData(current.map((i: any) => i.productNo));
    }

    if (
      goodsSourceRadio === SOURCE_OPTION.marketGoods.value &&
      goodsChooseRadio === GDCE_OPTION.handAuto.value
    ) {
      updateFromData([]);
    }

    // try {
    //   const { code, message: msg, data } = await querypullDownList(params);
    //   if (code === 0) {
    //     if (data.length > 0) {
    //       const goodsDisplayNum = wrapRef.current?.formRef.getFieldValue('goodsDisplayNum') || 0;
    //       const arrList: any = [];
    //       data.forEach((item: any, index: number) => {
    //         // if (goodsDisplayNum > index) {
    //         if (5 > index) {
    //           arrList.push({
    //             id: item.productNo,
    //             value: {
    //               ...item,
    //             },
    //           });
    //         }
    //       });
    //       // 自动时  selectInfo一直为[]
    //       setSelectInfo([]);
    //       updateFromData(arrList);
    //       updateCateInfo({ cateId: 0, secoundCateId: 0 });
    //     } else {
    //       setSelectInfo([]);
    //       updateFromData([]);
    //       updateCateInfo({ cateId: 0, secoundCateId: 0 });
    //     }
    //   } else {
    //     message.error(msg);
    //   }
    // } catch (error) {}
  };

  // 改变--商品来源、商品类目改变时重新查询
  useEffect(() => {
    const goodsSourceRadio = wrapRef.current?.formRef.getFieldValue('goodsSourceRadio');
    const goodsChooseRadio = wrapRef.current?.formRef.getFieldValue('goodsChooseRadio');
    if (
      goodsSourceRadio === SOURCE_OPTION.marketGoods.value &&
      goodsChooseRadio === GDCE_OPTION.handAuto.value
    ) {
      const goodsList = props.data.goodsData.reduce((r, i) => {
        const c = props.goodsList.find((g: any) => g.productNo === i);
        c && r.push(c);
        return r;
      }, [] as any[]);
      setSelectInfo(goodsList);
    }
    if (
      goodsSourceRadio === SOURCE_OPTION.marketGoods.value &&
      goodsChooseRadio === GDCE_OPTION.auto.value
    ) {
      initGoodsList();
    }
  }, []);

  // 修改类目时清空数据
  const handleSourceRadioChange = () => {
    dispatch({
      type: 'decoration/updateData',
      payload: { goodsCategory: '' },
    });
    wrapRef.current?.formRef.setFieldValue('goodsCategory', '');
  };

  // 选择商品--
  const handleChooseGoodsSubmit = (info: any) => {
    if (!info) return;
    if (info && info.goodsData.length > 20) {
      message.error('最多只能选择20个商品');
      return;
    }
    setChooseGoodsVisible(false);
    setSelectInfo(info.goodsData.map((i: any) => i.value));
    updateFromData(info.goodsData.map((i: any) => i.id));
    updateCateInfo({ cateId: info.cateId, secoundCateId: info.secoundCateId });
  };

  // 删除商品--
  const deleteGoodItem = (id: string) => {
    const selectInfoBro = selectInfo.filter((i: any) => i.productNo !== id);
    setSelectInfo(selectInfoBro);
    updateFromData(selectInfoBro.map((i: any) => i.productNo));
  };

  // 改变商品选择方式---清空商品数据
  const changeGoodsChooseRadio = (e: RadioChangeEvent) => {
    initGoodsList();
  };

  // 组件标题
  const changeTitleSwitch = (e: any) => {
    if (e) {
      wrapRef.current?.formRef.setFieldValue('title', '');
      dispatch({
        type: 'decoration/updateData',
        payload: { title: '' },
      });
    } else {
      wrapRef.current?.formRef.setFieldValue('title', '标题');
      dispatch({
        type: 'decoration/updateData',
        payload: { title: '标题' },
      });
    }
  };

  return (
    // @ts-ignore
    <WrapperForm<NavigationValue> ref={wrapRef} reducerName="updateData" {...props}>
      <div className={styles['title-switch']}>
        <ProFormSwitch
          label="组件标题"
          name="titleSwitch"
          checkedChildren="开"
          unCheckedChildren="关"
          required
          labelCol={{ span: 12 }}
          wrapperCol={{ span: 12 }}
          fieldProps={{
            onChange: changeTitleSwitch,
          }}
        />
      </div>
      <ProFormDependency name={['titleSwitch']}>
        {({ titleSwitch }) =>
          titleSwitch ? (
            <ProFormText
              label={null}
              name="title"
              placeholder="请输入标题"
              fieldProps={{ maxLength: 5, showCount: true }}
              rules={rules.title as Rule[]}
            />
          ) : null
        }
      </ProFormDependency>

      <ProFormItem label="选择模板" name="tplType" required rules={rules.tplType as Rule[]}>
        <ImageRadio options={values(TPL_TYPE)} />
      </ProFormItem>

      <ProFormDependency name={['tplType']}>
        {({ tplType }) =>
          [
            TPL_TYPE.oneLineAlbum.value,
            TPL_TYPE.threeLineAlbum.value,
            TPL_TYPE.scrollLeftAlbum.value,
          ].includes(tplType) ? (
            <FormJumpPage
              isShowTitle={false}
              name="album"
              maxLength={1}
              label={'设置专辑'}
              curListLength={wrapRef.current?.formRef?.getFieldValue('album')?.length || 0}
            />
          ) : null
        }
      </ProFormDependency>

      <ProFormDigit width={120} label="商品圆角" name="imgRadius" required />

      <ProFormRadio.Group
        label="商品选择方式"
        name="goodsChooseRadio"
        options={values(GDCE_OPTION)}
        required
        fieldProps={{
          onChange: changeGoodsChooseRadio,
        }}
      />

      <ProFormDependency name={['goodsChooseRadio', 'goodsNavSwitch', 'goodsData', 'cateInfo']}>
        {({ goodsChooseRadio, goodsNavSwitch, goodsData, cateInfo }) => {
          const goodsList = goodsData.reduce((r: any[], i: any) => {
            const c = props.goodsList.find((g: any) => g.productNo === i);
            c && r.push(c);
            return r;
          }, [] as any[]);

          const selected = selectInfo.map((s: any) => ({
            id: s.productNo,
            value: s,
          }));
          console.log(goodsList, goodsData, 'goodsList');
          return goodsChooseRadio === GDCE_OPTION.auto.value ? (
            <div>
              {/* <div className={styles['title-switch']}>
                <ProFormSwitch
                  label="商品导航"
                  name="goodsNavSwitch"
                  checkedChildren="开"
                  unCheckedChildren="关"
                  required
                  labelCol={{ span: 12 }}
                  wrapperCol={{ span: 12 }}
                />
              </div> */}

              <ProFormRadio.Group
                label="商品来源"
                name="goodsSourceRadio"
                options={values(SOURCE_OPTION)}
                fieldProps={{
                  onChange: handleSourceRadioChange,
                }}
                required
              />

              <ProFormDependency name={['goodsSourceRadio']}>
                {({ goodsSourceRadio }) => (
                  <ProFormSelect
                    // fieldProps={{
                    //   mode: 'tags',
                    // }}
                    name="goodsCategory"
                    label="商品类目"
                    required
                    placeholder="请选择"
                    options={
                      goodsSourceRadio === SOURCE_OPTION.marketGoods.value ? enumCategory : []
                    }
                    allowClear={false}
                    rules={[
                      {
                        validator: (_, _value) => {
                          if (_value !== 0 && !_value) {
                            return Promise.reject(new Error('请选择商品类目'));
                          }
                          if (goodsData.length === 0) {
                            return Promise.reject(new Error('该类目下没有商品，请重新选择'));
                          }
                          return Promise.resolve();
                        },
                      },
                    ]}
                  />
                )}
              </ProFormDependency>

              <ProFormDigit
                width={120}
                min={1}
                label={goodsNavSwitch ? '各类目商品展示数' : '商品展示数'}
                name="goodsDisplayNum"
                required
              />
            </div>
          ) : (
            <div>
              <div className={styles['add-btn']} onClick={() => setChooseGoodsVisible(true)}>
                <PlusOutlined />
                <span>添加商品</span>
                {goodsData.length}/20
              </div>

              {/* 选择商品 */}
              <ChooseGoods
                isMoreChoice={true}
                visible={chooseGoodsVisible}
                selectGoodsInfo={{
                  id: 0,
                  value: '',
                  goodsData: selected,
                  cateId: cateInfo.cateId || 0,
                  secoundCateId: cateInfo.secoundCateId || 0,
                }}
                confirmLoading={confirmLoading}
                onSubmit={handleChooseGoodsSubmit}
                onCancel={() => {
                  setChooseGoodsVisible(false);
                }}
              />

              <ProFormItem
                label={null}
                name="goodsData"
                rules={[
                  {
                    validator: (_, _value) => {
                      if (_value.length === 0) {
                        return Promise.reject(new Error('请添加商品'));
                      }
                      return Promise.resolve();
                    },
                  },
                ]}
              >
                <div className={styles['good-body']}>
                  {goodsList.map((item: any, index: number) => (
                    <Tag
                      key={`${item.productNo}-${index}`}
                      closable
                      onClose={() => {
                        deleteGoodItem(item.productNo);
                      }}
                      style={{ marginBottom: 8 }}
                    >
                      {item.productName}
                    </Tag>
                  ))}
                </div>
              </ProFormItem>
            </div>
          );
        }}
      </ProFormDependency>
      <ProFormDigit width={120} label="圆角" name="boxRadius" required />
      <div className={styles['set-display']}>
        <ProFormItem label="显示设置" required />
      </div>

      <ProFormItem label="背景设置" name="bgType">
        <Segmented options={values(BG_OPTION)} />
      </ProFormItem>

      <ProFormDependency name={['bgType']}>
        {({ bgType }) => {
          console.log(bgType);
          return (
            bgType === 1 && (
              <ProFormItem label="背景颜色" name="bgColor">
                <ColorPicker showText />
              </ProFormItem>
            )
          );
        }}
      </ProFormDependency>

      <ProFormItem label="标题色" name="titleColor">
        <ColorPicker showText />
      </ProFormItem>

      <div className={styles['title-switch']}>
        <ProFormSwitch
          label="原价"
          name="isShowOriginal"
          checkedChildren="展示"
          unCheckedChildren="不展示"
          labelCol={{ span: 12 }}
          wrapperCol={{ span: 12 }}
        />
      </div>
      <ProFormDependency name={['isShowOriginal']}>
        {({ isShowOriginal }) =>
          isShowOriginal ? (
            <div className={styles['color-picker']}>
              <ProFormItem label={null} name="originalPriceColor" required>
                <ColorPicker showText />
              </ProFormItem>
            </div>
          ) : null
        }
      </ProFormDependency>

      <div className={styles['title-switch']}>
        <ProFormSwitch
          label="活动价"
          name="isShowActivity"
          checkedChildren="展示"
          unCheckedChildren="不展示"
          labelCol={{ span: 12 }}
          wrapperCol={{ span: 12 }}
        />
      </div>
      <ProFormDependency name={['isShowActivity']}>
        {({ isShowActivity }) =>
          isShowActivity ? (
            <div className={styles['color-picker']}>
              <ProFormItem label={null} name="activityPriceColor" required>
                <ColorPicker showText />
              </ProFormItem>
            </div>
          ) : null
        }
      </ProFormDependency>

      <div className={styles['title-switch']}>
        <ProFormSwitch
          label="加购按钮"
          name="isShowAddBtn"
          checkedChildren="展示"
          unCheckedChildren="不展示"
          labelCol={{ span: 12 }}
          wrapperCol={{ span: 12 }}
        />
      </div>
      <ProFormDependency name={['isShowAddBtn']}>
        {({ isShowAddBtn }) =>
          isShowAddBtn ? (
            <div className={styles['color-picker']}>
              <ProFormItem label={null} name="addBtnColor" required>
                <ColorPicker showText />
              </ProFormItem>
            </div>
          ) : null
        }
      </ProFormDependency>

      <div className={styles['title-switch']}>
        <ProFormSwitch
          label="月销量"
          name="isShowMoonthSale"
          checkedChildren="展示"
          unCheckedChildren="不展示"
          labelCol={{ span: 12 }}
          wrapperCol={{ span: 12 }}
        />
      </div>
      <ProFormDependency name={['isShowMoonthSale']}>
        {({ isShowMoonthSale }) =>
          isShowMoonthSale ? (
            <div className={styles['color-picker']}>
              <ProFormItem label={null} name="moonthSaleColor" required>
                <ColorPicker showText />
              </ProFormItem>
            </div>
          ) : null
        }
      </ProFormDependency>

      <ProFormDependency name={['tplType']}>
        {({ tplType }) =>
          [TPL_TYPE.oneLine.value, TPL_TYPE.bigImg.value].includes(tplType) ? (
            <div style={{ paddingTop: '20px' }}>
              <ProFormItem
                label="间距"
                name="boxBorder"
                required
                className={styles['segment-father']}
              >
                <Segmented options={values(BOR_STYLE)} />
              </ProFormItem>
              <ProFormDigit width={120} label="圆角" name="boxRadius" required />
            </div>
          ) : null
        }
      </ProFormDependency>
    </WrapperForm>
  );
};

export default GoodsForm;
